"""
Agent间通信优化服务实现

提供智能Agent间通信和协作功能，包括：
- 智能消息路由算法
- 协作效率优化逻辑
- 通信质量监控机制
- Agent协作状态管理
"""
import json
import asyncio
import uuid
from typing import List, Dict, Any, Optional, Tuple, Set
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict, field
from collections import defaultdict, Counter, deque
from enum import Enum

from ..models.analysis_models import Context
from .agent_enhancement_service import AgentRole, AgentEnhancementService


class MessageType(Enum):
    """消息类型枚举"""
    REQUEST = "request"
    RESPONSE = "response"
    NOTIFICATION = "notification"
    COORDINATION = "coordination"
    STATUS_UPDATE = "status_update"
    RESOURCE_SHARE = "resource_share"
    KNOWLEDGE_SHARE = "knowledge_share"


class MessagePriority(Enum):
    """消息优先级枚举"""
    LOW = 1
    NORMAL = 2
    HIGH = 3
    URGENT = 4
    CRITICAL = 5


class CommunicationProtocol(Enum):
    """通信协议枚举"""
    DIRECT = "direct"
    BROADCAST = "broadcast"
    MULTICAST = "multicast"
    PUBLISH_SUBSCRIBE = "publish_subscribe"


@dataclass
class AgentMessage:
    """Agent消息"""
    message_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    sender_id: str = ""
    receiver_id: str = ""
    message_type: MessageType = MessageType.REQUEST
    priority: MessagePriority = MessagePriority.NORMAL
    protocol: CommunicationProtocol = CommunicationProtocol.DIRECT
    subject: str = ""
    content: Dict[str, Any] = field(default_factory=dict)
    context: Dict[str, Any] = field(default_factory=dict)
    timestamp: datetime = field(default_factory=datetime.now)
    expires_at: Optional[datetime] = None
    requires_response: bool = False
    response_timeout: int = 300  # 5分钟
    delivery_status: str = "pending"  # pending, delivered, failed, expired
    response_message_id: Optional[str] = None
@dataclas
s
class CommunicationChannel:
    """通信通道"""
    channel_id: str = ""
    name: str = ""
    participants: List[str] = field(default_factory=list)
    channel_type: str = "group"  # direct, group, broadcast
    is_active: bool = True
    created_at: datetime = field(default_factory=datetime.now)
    message_history: List[str] = field(default_factory=list)  # message_ids
    settings: Dict[str, Any] = field(default_factory=dict)


@dataclass
class CollaborationSession:
    """协作会话"""
    session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    name: str = ""
    participants: List[str] = field(default_factory=list)
    coordinator_id: str = ""
    session_type: str = "project"  # project, meeting, brainstorm
    status: str = "active"  # active, paused, completed, cancelled
    objectives: List[str] = field(default_factory=list)
    shared_resources: Dict[str, Any] = field(default_factory=dict)
    decisions_made: List[Dict[str, Any]] = field(default_factory=list)
    start_time: datetime = field(default_factory=datetime.now)
    end_time: Optional[datetime] = None
    metrics: Dict[str, float] = field(default_factory=dict)


@dataclass
class CommunicationMetrics:
    """通信指标"""
    agent_id: str = ""
    period_start: datetime = field(default_factory=datetime.now)
    period_end: datetime = field(default_factory=datetime.now)
    messages_sent: int = 0
    messages_received: int = 0
    response_time_avg: float = 0.0
    collaboration_score: float = 0.0
    communication_efficiency: float = 0.0
    successful_interactions: int = 0
    failed_interactions: int = 0
cl
ass AgentCommunicationService:
    """Agent间通信优化服务"""
    
    def __init__(self, agent_enhancement_service: Optional[AgentEnhancementService] = None):
        self.agent_enhancement_service = agent_enhancement_service or AgentEnhancementService()
        
        # 消息管理
        self.message_queue: Dict[str, deque] = defaultdict(deque)  # agent_id -> messages
        self.message_history: Dict[str, AgentMessage] = {}  # message_id -> message
        self.pending_responses: Dict[str, AgentMessage] = {}  # message_id -> original_message
        
        # 通信通道管理
        self.communication_channels: Dict[str, CommunicationChannel] = {}
        self.agent_channels: Dict[str, List[str]] = defaultdict(list)  # agent_id -> channel_ids
        
        # 协作会话管理
        self.collaboration_sessions: Dict[str, CollaborationSession] = {}
        self.active_sessions: Dict[str, str] = {}  # agent_id -> session_id
        
        # 通信指标和监控
        self.communication_metrics: Dict[str, CommunicationMetrics] = {}
        self.routing_table: Dict[Tuple[str, str], List[str]] = {}  # (sender, receiver) -> path
        
        # 通信配置
        self.communication_config = {
            'max_queue_size': 1000,
            'message_ttl_hours': 24,
            'response_timeout_seconds': 300,
            'max_retry_attempts': 3,
            'routing_optimization_interval': 3600,  # 1小时
            'metrics_update_interval': 300,  # 5分钟
            'collaboration_timeout_hours': 8
        }
        
        # 消息路由规则
        self.routing_rules = {
            AgentRole.PROFESSOR: {
                'can_coordinate': [AgentRole.PHD_STUDENT, AgentRole.ML_ENGINEER, AgentRole.POSTDOC],
                'receives_reports': True,
                'priority_boost': 1
            },
            AgentRole.PHD_STUDENT: {
                'reports_to': [AgentRole.PROFESSOR, AgentRole.POSTDOC],
                'collaborates_with': [AgentRole.PHD_STUDENT, AgentRole.ML_ENGINEER],
                'priority_boost': 0
            },
            AgentRole.ML_ENGINEER: {
                'reports_to': [AgentRole.PROFESSOR],
                'collaborates_with': [AgentRole.PHD_STUDENT, AgentRole.ML_ENGINEER],
                'provides_support': True,
                'priority_boost': 0
            }
        } 
   async def send_message(self, message: AgentMessage) -> bool:
        """发送消息"""
        try:
            # 验证消息
            if not await self._validate_message(message):
                return False
            
            # 应用智能路由
            optimized_message = await self._apply_intelligent_routing(message)
            
            # 设置过期时间
            if not optimized_message.expires_at:
                ttl_hours = self.communication_config['message_ttl_hours']
                optimized_message.expires_at = datetime.now() + timedelta(hours=ttl_hours)
            
            # 存储消息
            self.message_history[optimized_message.message_id] = optimized_message
            
            # 根据协议发送消息
            success = await self._deliver_message(optimized_message)
            
            if success:
                optimized_message.delivery_status = "delivered"
                
                # 如果需要响应，添加到待响应列表
                if optimized_message.requires_response:
                    self.pending_responses[optimized_message.message_id] = optimized_message
                
                # 更新通信指标
                await self._update_communication_metrics(optimized_message.sender_id, 'sent')
                
            else:
                optimized_message.delivery_status = "failed"
            
            return success
            
        except Exception as e:
            print(f"发送消息失败: {e}")
            return False
    
    async def receive_message(self, agent_id: str) -> Optional[AgentMessage]:
        """接收消息"""
        try:
            if agent_id not in self.message_queue or not self.message_queue[agent_id]:
                return None
            
            # 从队列中取出消息
            message = self.message_queue[agent_id].popleft()
            
            # 检查消息是否过期
            if message.expires_at and datetime.now() > message.expires_at:
                message.delivery_status = "expired"
                return None
            
            # 更新通信指标
            await self._update_communication_metrics(agent_id, 'received')
            
            return message
            
        except Exception as e:
            print(f"接收消息失败: {e}")
            return None   
 async def send_response(self, original_message_id: str, response_content: Dict[str, Any], 
                          sender_id: str) -> bool:
        """发送响应消息"""
        try:
            if original_message_id not in self.pending_responses:
                return False
            
            original_message = self.pending_responses[original_message_id]
            
            # 创建响应消息
            response_message = AgentMessage(
                sender_id=sender_id,
                receiver_id=original_message.sender_id,
                message_type=MessageType.RESPONSE,
                priority=original_message.priority,
                subject=f"Re: {original_message.subject}",
                content=response_content,
                context={'original_message_id': original_message_id}
            )
            
            # 发送响应
            success = await self.send_message(response_message)
            
            if success:
                # 更新原消息的响应ID
                original_message.response_message_id = response_message.message_id
                
                # 从待响应列表中移除
                del self.pending_responses[original_message_id]
            
            return success
            
        except Exception as e:
            print(f"发送响应失败: {e}")
            return False
    
    async def create_collaboration_session(self, coordinator_id: str, participants: List[str],
                                         session_name: str, objectives: List[str]) -> str:
        """创建协作会话"""
        try:
            session = CollaborationSession(
                name=session_name,
                participants=participants + [coordinator_id],
                coordinator_id=coordinator_id,
                objectives=objectives
            )
            
            self.collaboration_sessions[session.session_id] = session
            
            # 更新参与者的活跃会话
            for participant in session.participants:
                self.active_sessions[participant] = session.session_id
            
            # 创建会话通信通道
            channel = CommunicationChannel(
                channel_id=f"session_{session.session_id}",
                name=f"Session: {session_name}",
                participants=session.participants,
                channel_type="group"
            )
            
            await self.create_communication_channel(channel)
            
            # 发送会话开始通知
            for participant in participants:
                notification = AgentMessage(
                    sender_id=coordinator_id,
                    receiver_id=participant,
                    message_type=MessageType.NOTIFICATION,
                    priority=MessagePriority.HIGH,
                    subject=f"协作会话开始: {session_name}",
                    content={
                        'session_id': session.session_id,
                        'objectives': objectives,
                        'coordinator': coordinator_id
                    }
                )
                await self.send_message(notification)
            
            return session.session_id
            
        except Exception as e:
            print(f"创建协作会话失败: {e}")
            return ""    
async def create_communication_channel(self, channel: CommunicationChannel) -> bool:
        """创建通信通道"""
        try:
            self.communication_channels[channel.channel_id] = channel
            
            # 更新参与者的通道列表
            for participant in channel.participants:
                self.agent_channels[participant].append(channel.channel_id)
            
            return True
            
        except Exception as e:
            print(f"创建通信通道失败: {e}")
            return False
    
    async def _validate_message(self, message: AgentMessage) -> bool:
        """验证消息"""
        if not message.sender_id or not message.receiver_id:
            return False
        
        if message.sender_id == message.receiver_id:
            return False
        
        if not message.subject and message.message_type != MessageType.STATUS_UPDATE:
            return False
        
        return True
    
    async def _apply_intelligent_routing(self, message: AgentMessage) -> AgentMessage:
        """应用智能路由"""
        try:
            # 获取发送者和接收者的角色
            sender_role = await self._get_agent_role(message.sender_id)
            receiver_role = await self._get_agent_role(message.receiver_id)
            
            # 应用路由规则
            if sender_role and receiver_role:
                # 检查是否需要优先级提升
                sender_rules = self.routing_rules.get(sender_role, {})
                priority_boost = sender_rules.get('priority_boost', 0)
                
                if priority_boost > 0:
                    new_priority_value = min(message.priority.value + priority_boost, 5)
                    message.priority = MessagePriority(new_priority_value)
                
                # 检查通信权限
                if not await self._check_communication_permission(sender_role, receiver_role, message.message_type):
                    print(f"通信权限检查失败: {sender_role} -> {receiver_role}")
            
            # 优化消息内容
            message = await self._optimize_message_content(message)
            
            return message
            
        except Exception as e:
            print(f"智能路由失败: {e}")
            return message
    
    async def _deliver_message(self, message: AgentMessage) -> bool:
        """投递消息"""
        try:
            if message.protocol == CommunicationProtocol.DIRECT:
                return await self._deliver_direct_message(message)
            elif message.protocol == CommunicationProtocol.BROADCAST:
                return await self._deliver_broadcast_message(message)
            elif message.protocol == CommunicationProtocol.MULTICAST:
                return await self._deliver_multicast_message(message)
            else:
                return await self._deliver_direct_message(message)
                
        except Exception as e:
            print(f"消息投递失败: {e}")
            return False 
   async def _deliver_direct_message(self, message: AgentMessage) -> bool:
        """直接消息投递"""
        try:
            receiver_queue = self.message_queue[message.receiver_id]
            
            # 检查队列大小
            max_size = self.communication_config['max_queue_size']
            if len(receiver_queue) >= max_size:
                # 移除最旧的低优先级消息
                await self._cleanup_message_queue(message.receiver_id)
            
            # 按优先级插入消息
            await self._insert_message_by_priority(receiver_queue, message)
            
            return True
            
        except Exception as e:
            print(f"直接消息投递失败: {e}")
            return False
    
    async def _deliver_broadcast_message(self, message: AgentMessage) -> bool:
        """广播消息投递"""
        try:
            # 获取所有活跃的Agent
            all_agents = set(self.message_queue.keys())
            all_agents.discard(message.sender_id)  # 排除发送者
            
            success_count = 0
            for agent_id in all_agents:
                # 创建消息副本
                broadcast_message = AgentMessage(
                    sender_id=message.sender_id,
                    receiver_id=agent_id,
                    message_type=message.message_type,
                    priority=message.priority,
                    protocol=CommunicationProtocol.DIRECT,
                    subject=message.subject,
                    content=message.content.copy(),
                    context=message.context.copy()
                )
                
                if await self._deliver_direct_message(broadcast_message):
                    success_count += 1
            
            return success_count > 0
            
        except Exception as e:
            print(f"广播消息投递失败: {e}")
            return False
    
    async def _deliver_multicast_message(self, message: AgentMessage) -> bool:
        """组播消息投递"""
        try:
            # 从消息内容中获取接收者列表
            receivers = message.content.get('receivers', [])
            if not receivers:
                return False
            
            success_count = 0
            for receiver_id in receivers:
                if receiver_id != message.sender_id:
                    multicast_message = AgentMessage(
                        sender_id=message.sender_id,
                        receiver_id=receiver_id,
                        message_type=message.message_type,
                        priority=message.priority,
                        protocol=CommunicationProtocol.DIRECT,
                        subject=message.subject,
                        content=message.content.copy(),
                        context=message.context.copy()
                    )
                    
                    if await self._deliver_direct_message(multicast_message):
                        success_count += 1
            
            return success_count > 0
            
        except Exception as e:
            print(f"组播消息投递失败: {e}")
            return False  
  async def _insert_message_by_priority(self, queue: deque, message: AgentMessage):
        """按优先级插入消息"""
        # 如果队列为空或消息优先级最低，直接添加到末尾
        if not queue or message.priority.value <= queue[-1].priority.value:
            queue.append(message)
            return
        
        # 找到合适的插入位置
        for i, existing_message in enumerate(queue):
            if message.priority.value > existing_message.priority.value:
                queue.insert(i, message)
                return
        
        # 如果没有找到合适位置，添加到末尾
        queue.append(message)
    
    async def _cleanup_message_queue(self, agent_id: str):
        """清理消息队列"""
        queue = self.message_queue[agent_id]
        
        # 移除过期消息
        current_time = datetime.now()
        expired_messages = []
        
        for i, message in enumerate(queue):
            if message.expires_at and current_time > message.expires_at:
                expired_messages.append(i)
        
        # 从后往前删除，避免索引问题
        for i in reversed(expired_messages):
            del queue[i]
        
        # 如果队列仍然太大，移除最旧的低优先级消息
        max_size = self.communication_config['max_queue_size']
        while len(queue) >= max_size:
            # 找到最旧的低优先级消息
            min_priority = min(msg.priority.value for msg in queue)
            for i, message in enumerate(queue):
                if message.priority.value == min_priority:
                    del queue[i]
                    break
    
    async def _get_agent_role(self, agent_id: str) -> Optional[AgentRole]:
        """获取Agent角色"""
        # 简化实现：从agent_id中推断角色
        if 'professor' in agent_id.lower():
            return AgentRole.PROFESSOR
        elif 'phd' in agent_id.lower() or 'student' in agent_id.lower():
            return AgentRole.PHD_STUDENT
        elif 'ml' in agent_id.lower() or 'engineer' in agent_id.lower():
            return AgentRole.ML_ENGINEER
        elif 'postdoc' in agent_id.lower():
            return AgentRole.POSTDOC
        elif 'reviewer' in agent_id.lower():
            return AgentRole.REVIEWER
        else:
            return None
    
    async def _check_communication_permission(self, sender_role: AgentRole, 
                                            receiver_role: AgentRole, 
                                            message_type: MessageType) -> bool:
        """检查通信权限"""
        sender_rules = self.routing_rules.get(sender_role, {})
        
        # 检查协调权限
        if message_type == MessageType.COORDINATION:
            can_coordinate = sender_rules.get('can_coordinate', [])
            return receiver_role in can_coordinate
        
        # 检查报告权限
        if message_type == MessageType.STATUS_UPDATE:
            reports_to = sender_rules.get('reports_to', [])
            return receiver_role in reports_to or sender_role == AgentRole.PROFESSOR
        
        # 检查协作权限
        if message_type in [MessageType.REQUEST, MessageType.KNOWLEDGE_SHARE]:
            collaborates_with = sender_rules.get('collaborates_with', [])
            return receiver_role in collaborates_with or receiver_role == sender_role
        
        # 默认允许通知和响应
        return True 
   async def _optimize_message_content(self, message: AgentMessage) -> AgentMessage:
        """优化消息内容"""
        try:
            # 压缩重复内容
            if 'data' in message.content and isinstance(message.content['data'], list):
                # 移除重复项
                message.content['data'] = list(dict.fromkeys(message.content['data']))
            
            # 添加上下文信息
            if not message.context.get('timestamp'):
                message.context['timestamp'] = message.timestamp.isoformat()
            
            # 添加路由信息
            message.context['routing_path'] = [message.sender_id, message.receiver_id]
            
            return message
            
        except Exception as e:
            print(f"消息内容优化失败: {e}")
            return message
    
    async def _update_communication_metrics(self, agent_id: str, action: str):
        """更新通信指标"""
        try:
            if agent_id not in self.communication_metrics:
                self.communication_metrics[agent_id] = CommunicationMetrics(agent_id=agent_id)
            
            metrics = self.communication_metrics[agent_id]
            
            if action == 'sent':
                metrics.messages_sent += 1
            elif action == 'received':
                metrics.messages_received += 1
            
            # 更新时间戳
            metrics.period_end = datetime.now()
            
        except Exception as e:
            print(f"更新通信指标失败: {e}")
    
    async def get_communication_metrics(self, agent_id: str, days: int = 7) -> Dict[str, Any]:
        """获取通信指标"""
        try:
            if agent_id not in self.communication_metrics:
                return {'error': '没有通信数据'}
            
            metrics = self.communication_metrics[agent_id]
            cutoff_date = datetime.now() - timedelta(days=days)
            
            # 计算响应时间
            response_times = []
            for message_id, message in self.message_history.items():
                if (message.sender_id == agent_id and 
                    message.response_message_id and 
                    message.timestamp > cutoff_date):
                    
                    response_msg = self.message_history.get(message.response_message_id)
                    if response_msg:
                        response_time = (response_msg.timestamp - message.timestamp).total_seconds()
                        response_times.append(response_time)
            
            avg_response_time = sum(response_times) / len(response_times) if response_times else 0
            
            # 计算协作分数
            collaboration_score = await self._calculate_collaboration_score(agent_id, days)
            
            # 计算通信效率
            total_messages = metrics.messages_sent + metrics.messages_received
            successful_responses = len(response_times)
            efficiency = successful_responses / total_messages if total_messages > 0 else 0
            
            return {
                'agent_id': agent_id,
                'period_days': days,
                'messages_sent': metrics.messages_sent,
                'messages_received': metrics.messages_received,
                'average_response_time_seconds': avg_response_time,
                'collaboration_score': collaboration_score,
                'communication_efficiency': efficiency,
                'active_channels': len(self.agent_channels.get(agent_id, [])),
                'pending_responses': len([m for m in self.pending_responses.values() 
                                        if m.receiver_id == agent_id])
            }
            
        except Exception as e:
            print(f"获取通信指标失败: {e}")
            return {'error': '通信指标获取失败'}  
  async def _calculate_collaboration_score(self, agent_id: str, days: int) -> float:
        """计算协作分数"""
        try:
            cutoff_date = datetime.now() - timedelta(days=days)
            
            # 统计协作相关的消息
            collaboration_messages = 0
            total_messages = 0
            
            for message in self.message_history.values():
                if ((message.sender_id == agent_id or message.receiver_id == agent_id) and 
                    message.timestamp > cutoff_date):
                    
                    total_messages += 1
                    
                    if message.message_type in [MessageType.COORDINATION, 
                                              MessageType.KNOWLEDGE_SHARE, 
                                              MessageType.RESOURCE_SHARE]:
                        collaboration_messages += 1
            
            # 计算参与的协作会话数
            active_sessions = 0
            for session in self.collaboration_sessions.values():
                if (agent_id in session.participants and 
                    session.start_time > cutoff_date):
                    active_sessions += 1
            
            # 综合计算协作分数
            message_score = collaboration_messages / total_messages if total_messages > 0 else 0
            session_score = min(active_sessions / 5, 1.0)  # 最多5个会话得满分
            
            return (message_score * 0.7 + session_score * 0.3)
            
        except Exception as e:
            print(f"计算协作分数失败: {e}")
            return 0.0
    
    async def optimize_communication_routes(self) -> Dict[str, Any]:
        """优化通信路由"""
        try:
            optimization_results = {
                'routes_optimized': 0,
                'efficiency_improvement': 0.0,
                'bottlenecks_resolved': 0
            }
            
            # 分析通信模式
            communication_patterns = await self._analyze_communication_patterns()
            
            # 识别通信瓶颈
            bottlenecks = await self._identify_communication_bottlenecks()
            
            # 优化路由表
            for (sender, receiver), current_path in self.routing_table.items():
                optimized_path = await self._optimize_route(sender, receiver, communication_patterns)
                
                if optimized_path != current_path:
                    self.routing_table[(sender, receiver)] = optimized_path
                    optimization_results['routes_optimized'] += 1
            
            # 解决瓶颈
            for bottleneck in bottlenecks:
                if await self._resolve_bottleneck(bottleneck):
                    optimization_results['bottlenecks_resolved'] += 1
            
            return optimization_results
            
        except Exception as e:
            print(f"优化通信路由失败: {e}")
            return {'error': '路由优化失败'}
    
    async def _analyze_communication_patterns(self) -> Dict[str, Any]:
        """分析通信模式"""
        patterns = {
            'frequent_pairs': Counter(),
            'peak_hours': Counter(),
            'message_types': Counter(),
            'response_times': defaultdict(list)
        }
        
        try:
            cutoff_date = datetime.now() - timedelta(days=7)
            
            for message in self.message_history.values():
                if message.timestamp > cutoff_date:
                    # 统计频繁通信对
                    pair = (message.sender_id, message.receiver_id)
                    patterns['frequent_pairs'][pair] += 1
                    
                    # 统计高峰时段
                    hour = message.timestamp.hour
                    patterns['peak_hours'][hour] += 1
                    
                    # 统计消息类型
                    patterns['message_types'][message.message_type.value] += 1
                    
                    # 统计响应时间
                    if message.response_message_id:
                        response_msg = self.message_history.get(message.response_message_id)
                        if response_msg:
                            response_time = (response_msg.timestamp - message.timestamp).total_seconds()
                            patterns['response_times'][pair].append(response_time)
            
        except Exception as e:
            print(f"分析通信模式失败: {e}")
        
        return patterns    as
ync def _identify_communication_bottlenecks(self) -> List[Dict[str, Any]]:
        """识别通信瓶颈"""
        bottlenecks = []
        
        try:
            # 检查消息队列长度
            for agent_id, queue in self.message_queue.items():
                if len(queue) > self.communication_config['max_queue_size'] * 0.8:
                    bottlenecks.append({
                        'type': 'queue_overflow',
                        'agent_id': agent_id,
                        'queue_size': len(queue),
                        'severity': 'high' if len(queue) > self.communication_config['max_queue_size'] * 0.9 else 'medium'
                    })
            
            # 检查响应超时
            current_time = datetime.now()
            timeout_threshold = self.communication_config['response_timeout_seconds']
            
            for message_id, message in self.pending_responses.items():
                time_elapsed = (current_time - message.timestamp).total_seconds()
                if time_elapsed > timeout_threshold:
                    bottlenecks.append({
                        'type': 'response_timeout',
                        'message_id': message_id,
                        'sender_id': message.sender_id,
                        'receiver_id': message.receiver_id,
                        'elapsed_time': time_elapsed,
                        'severity': 'high'
                    })
            
            # 检查通信频率异常
            patterns = await self._analyze_communication_patterns()
            avg_frequency = sum(patterns['frequent_pairs'].values()) / len(patterns['frequent_pairs']) if patterns['frequent_pairs'] else 0
            
            for pair, frequency in patterns['frequent_pairs'].items():
                if frequency > avg_frequency * 3:  # 频率异常高
                    bottlenecks.append({
                        'type': 'high_frequency',
                        'sender_id': pair[0],
                        'receiver_id': pair[1],
                        'frequency': frequency,
                        'severity': 'medium'
                    })
            
        except Exception as e:
            print(f"识别通信瓶颈失败: {e}")
        
        return bottlenecks
    
    async def _optimize_route(self, sender: str, receiver: str, patterns: Dict[str, Any]) -> List[str]:
        """优化路由"""
        # 简化实现：直接路由
        return [sender, receiver]
    
    async def _resolve_bottleneck(self, bottleneck: Dict[str, Any]) -> bool:
        """解决瓶颈"""
        try:
            if bottleneck['type'] == 'queue_overflow':
                agent_id = bottleneck['agent_id']
                await self._cleanup_message_queue(agent_id)
                return True
            
            elif bottleneck['type'] == 'response_timeout':
                message_id = bottleneck['message_id']
                if message_id in self.pending_responses:
                    # 标记为超时并移除
                    message = self.pending_responses[message_id]
                    message.delivery_status = 'timeout'
                    del self.pending_responses[message_id]
                return True
            
            elif bottleneck['type'] == 'high_frequency':
                # 可以实现频率限制或批量处理
                return True
            
        except Exception as e:
            print(f"解决瓶颈失败: {e}")
        
        return False
    
    async def get_collaboration_session_status(self, session_id: str) -> Dict[str, Any]:
        """获取协作会话状态"""
        try:
            if session_id not in self.collaboration_sessions:
                return {'error': '会话不存在'}
            
            session = self.collaboration_sessions[session_id]
            
            # 计算会话指标
            duration = datetime.now() - session.start_time
            message_count = len(session.shared_resources.get('messages', []))
            
            # 计算参与度
            participation_scores = {}
            for participant in session.participants:
                # 统计该参与者在会话中的消息数
                participant_messages = 0
                for message in self.message_history.values():
                    if (message.sender_id == participant and 
                        message.timestamp >= session.start_time and
                        message.context.get('session_id') == session_id):
                        participant_messages += 1
                
                participation_scores[participant] = participant_messages
            
            return {
                'session_id': session_id,
                'name': session.name,
                'status': session.status,
                'participants': session.participants,
                'coordinator': session.coordinator_id,
                'duration_minutes': duration.total_seconds() / 60,
                'objectives_completed': len([obj for obj in session.objectives if 'completed' in obj]),
                'total_objectives': len(session.objectives),
                'message_count': message_count,
                'decisions_made': len(session.decisions_made),
                'participation_scores': participation_scores,
                'shared_resources_count': len(session.shared_resources)
            }
            
        except Exception as e:
            print(f"获取协作会话状态失败: {e}")
            return {'error': '获取会话状态失败'}    a
sync def end_collaboration_session(self, session_id: str, coordinator_id: str) -> bool:
        """结束协作会话"""
        try:
            if session_id not in self.collaboration_sessions:
                return False
            
            session = self.collaboration_sessions[session_id]
            
            # 验证权限
            if session.coordinator_id != coordinator_id:
                return False
            
            # 更新会话状态
            session.status = "completed"
            session.end_time = datetime.now()
            
            # 计算会话指标
            duration = session.end_time - session.start_time
            session.metrics = {
                'duration_minutes': duration.total_seconds() / 60,
                'objectives_completed': len([obj for obj in session.objectives if 'completed' in obj]),
                'total_messages': len(session.shared_resources.get('messages', [])),
                'decisions_made': len(session.decisions_made)
            }
            
            # 清理活跃会话记录
            for participant in session.participants:
                if self.active_sessions.get(participant) == session_id:
                    del self.active_sessions[participant]
            
            # 发送会话结束通知
            for participant in session.participants:
                if participant != coordinator_id:
                    notification = AgentMessage(
                        sender_id=coordinator_id,
                        receiver_id=participant,
                        message_type=MessageType.NOTIFICATION,
                        priority=MessagePriority.NORMAL,
                        subject=f"协作会话结束: {session.name}",
                        content={
                            'session_id': session_id,
                            'duration_minutes': session.metrics['duration_minutes'],
                            'objectives_completed': session.metrics['objectives_completed'],
                            'summary': '会话已成功完成'
                        }
                    )
                    await self.send_message(notification)
            
            return True
            
        except Exception as e:
            print(f"结束协作会话失败: {e}")
            return False
    
    async def export_communication_data(self, agent_id: str) -> Dict[str, Any]:
        """导出通信数据"""
        try:
            export_data = {
                'agent_id': agent_id,
                'export_date': datetime.now().isoformat(),
                'messages': [],
                'channels': [],
                'sessions': [],
                'metrics': {}
            }
            
            # 导出消息历史
            for message in self.message_history.values():
                if message.sender_id == agent_id or message.receiver_id == agent_id:
                    export_data['messages'].append(asdict(message))
            
            # 导出通信通道
            agent_channel_ids = self.agent_channels.get(agent_id, [])
            for channel_id in agent_channel_ids:
                if channel_id in self.communication_channels:
                    export_data['channels'].append(asdict(self.communication_channels[channel_id]))
            
            # 导出协作会话
            for session in self.collaboration_sessions.values():
                if agent_id in session.participants:
                    export_data['sessions'].append(asdict(session))
            
            # 导出通信指标
            if agent_id in self.communication_metrics:
                export_data['metrics'] = asdict(self.communication_metrics[agent_id])
            
            return export_data
            
        except Exception as e:
            print(f"导出通信数据失败: {e}")
            return {'error': '通信数据导出失败'}
    
    async def delete_communication_data(self, agent_id: str) -> bool:
        """删除通信数据"""
        try:
            # 删除消息队列
            if agent_id in self.message_queue:
                del self.message_queue[agent_id]
            
            # 删除相关消息历史
            messages_to_delete = []
            for message_id, message in self.message_history.items():
                if message.sender_id == agent_id or message.receiver_id == agent_id:
                    messages_to_delete.append(message_id)
            
            for message_id in messages_to_delete:
                del self.message_history[message_id]
            
            # 删除待响应消息
            responses_to_delete = []
            for message_id, message in self.pending_responses.items():
                if message.sender_id == agent_id or message.receiver_id == agent_id:
                    responses_to_delete.append(message_id)
            
            for message_id in responses_to_delete:
                del self.pending_responses[message_id]
            
            # 删除通信通道
            if agent_id in self.agent_channels:
                for channel_id in self.agent_channels[agent_id]:
                    if channel_id in self.communication_channels:
                        channel = self.communication_channels[channel_id]
                        channel.participants.remove(agent_id)
                        if not channel.participants:
                            del self.communication_channels[channel_id]
                
                del self.agent_channels[agent_id]
            
            # 删除协作会话
            sessions_to_delete = []
            for session_id, session in self.collaboration_sessions.items():
                if agent_id in session.participants:
                    session.participants.remove(agent_id)
                    if not session.participants:
                        sessions_to_delete.append(session_id)
            
            for session_id in sessions_to_delete:
                del self.collaboration_sessions[session_id]
            
            # 删除活跃会话记录
            if agent_id in self.active_sessions:
                del self.active_sessions[agent_id]
            
            # 删除通信指标
            if agent_id in self.communication_metrics:
                del self.communication_metrics[agent_id]
            
            return True
            
        except Exception as e:
            print(f"删除通信数据失败: {e}")
            return False